package org.zhangxf.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * @AUTHOR zhangxf
 * @CREATE 2020-03-17 00:34
 */
public class NettyChatServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            serverBootstrap.group(bossGroup, workGroup)
                    //服务端的是NioServerSocketChannel
                    .channel(NioServerSocketChannel.class)
                    //option设置服务器配置项
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //childOption设置客户端请求配置项
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    //handler处理服务端的，childHandler处理客户端的
                    //处理的都是SocketChannel
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //注意此处in和out的顺序，最后一个in后面的out不会执行
                            // 一般自己写的handler放最后
                            // in1 -> in2 -> in3
                            // out3 <- out2 <- out1
                            // in推荐使用addFirst，out使用addLast
                            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                            pipeline.addFirst(new StringEncoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new NettyChatServerHandler());
                        }
                    });
            //ChannelFuture为异步调用，使用async阻塞确保服务启动完成
            ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {

            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
